import { Component, OnInit } from '@angular/core';
import { EChartOption } from 'echarts';
import { differenceInCalendarDays } from 'date-fns';
import { TranslateService } from '@ngx-translate/core';
import * as moment from 'moment';
import { ToolsService } from 'app/shared/service';
import { DataVisualizationService } from 'app/pages/data-visualization/dataVisualization.service';
import { color } from 'html2canvas/dist/types/css/types/color';

@Component({
    selector: 'itmp-incident',
    templateUrl: './incident.component.html',
    styleUrls: ['./incident.component.css']
})
export class IncidentComponent implements OnInit {
    options: EChartOption;
    searchData: any;
    updatedDate = [];
    series: any;
    dateFormat = 'MM/yyyy';
    placeHodlder = ['Start Time', 'End Time'];
    legendData: any;
    startDefaultTime = new Date(Date.now() - 1000 * 60 * 60 * 24 * 365);
    endDefaultTime = new Date();

    test: 'hahah1';
    constructor(private ds: DataVisualizationService, private translate: TranslateService, private tools: ToolsService) {}

    ngOnInit() {
        this.initData();
        this.translate.onLangChange.subscribe(() => this._getData());
    }
    initData() {
        // const date = new Date();
        const startTime = new Date(this.startDefaultTime);
        const endTime = new Date(this.endDefaultTime);
        this.updatedDate = [startTime, endTime];
        this.searchData = {
            interval: 'Weekly',
            startTime,
            endTime
        };
        this.placeHodlder = ['Up to', 'two years'];
        this.filter(this.searchData.interval);
    }
    formatDate(date) {
        const newDate = new Date(date);
        const y = newDate.getFullYear();
        const m = newDate.getMonth() + 1;
        const d = newDate.getDate();
        return `${y < 10 ? '0' + y : y}-${m < 10 ? '0' + m : m}-${d < 10 ? '0' + d : d}`;
    }
    _getData() {
        const params = [];
        for (const key in this.searchData) {
            if (this.searchData.hasOwnProperty(key)) {
                const element = this.searchData[key];
                params.push(
                    `${key}=${
                        key !== 'interval'
                            ? this.formatDate(element)
                            : (() => {
                                  let interval;
                                  switch (element) {
                                      case 'Monthly':
                                          interval = 'mm';
                                          break;
                                      case 'Weekly':
                                          interval = 'wk';
                                          break;
                                      case 'Yearly':
                                          interval = 'mm';
                                          break;
                                  }
                                  return interval;
                              })()
                    }`
                );
            }
        }
        let queryNO = 116;
        if (params[0] === 'interval=wk') {
            params.splice(0, 1);
            queryNO = 119;
        }
        if (this.searchData.interval === 'Yearly') {
            queryNO = 118;
        }

        if (queryNO === 118) {
            this.ds.getIncidentAnalyticsYearReport(queryNO, params.join(',')).subscribe(res => {
                if (res.messagecode === '000000') {
                    this._setYearlyOptions(res.data);
                }
            });
        } else if (queryNO === 119) {
            this.ds.getIncidentAnalyticsWeekReport(queryNO, '').subscribe(res => {
                this.series = [];
                this.legendData = [];
                if (res.messagecode === '000000') {
                    this._setWeeklyOptions(res.data);
                }
            });
        } else {
            this.ds.getIncidentAnalyticsReport(queryNO, params.join(',')).subscribe(res => {
                this.series = [];
                this.legendData = [];
                if (res.messagecode === '000000') {
                    switch (this.searchData.interval) {
                        case 'Monthly':
                            this._setMonthlyOptions(res.data);
                            break;
                        case 'Weekly':
                            this._setWeeklyOptions(res.data);
                            break;
                    }
                }
            });
        }
    }
    // 按月展示
    _setMonthlyOptions(data) {
        const legendData = [];
        const series = [];
        data.forEach(item => {
            const year = item.interval_zone.slice(0, 4);
            const month = item.interval_zone.slice(5, 7);
            let has = false;
            legendData.forEach(m => {
                if (year === m.name) {
                    has = true;
                    return;
                }
            });
            if (!has) {
                legendData.push({ name: year, icon: 'circle' });
                series.push({
                    name: year,
                    type: 'line',
                    stack: '总量',
                    data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                });
            }
            series.forEach(n => {
                if (n.name === year) {
                    n.data[month - 1] = item.total;
                }
            });
        });
        const tempData = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        const tempTranslete = [];
        tempData.forEach(item => {
            this.translate.get('Data_Visualization.Overall.' + item).subscribe((res: string) => {
                tempTranslete.push(res);
            });
        });
        setTimeout(() => {
            this.options = {
                xAxis: {
                    show: true,
                    type: 'category',
                    boundaryGap: false,
                    splitLine: {
                        show: true
                    },
                    data: tempTranslete
                },
                yAxis: {
                    show: true,
                    type: 'value',
                    splitLine: {
                        show: true
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    // formatter: '{b}  {a}: {c}',
                    backgroundColor: 'rgba(0,71,157,0.5)'
                },
                legend: {
                    right: 10,
                    data: legendData
                },
                color: ['rgba(42,49,67,0.5)', '#238CE6'],
                series
            };
        });
    }
    // 生成x轴
    _displayXais(data: Array<{}>) {
        const arr = [];
        const startTime = new Date(this.updatedDate[0]).getTime();
        const endTime = new Date(this.updatedDate[1]).getTime();
        // 向右拼接数据
        function toRight(st) {
            const newItem = st + 7 * 24 * 60 * 60 * 1000;
            if (newItem < endTime) {
                arr.push([st, newItem]);
                toRight(newItem);
            }
        }
        // 向左拼接数据
        function toLeftReverse(st) {
            const newItem = st - 7 * 24 * 60 * 60 * 1000;
            if (newItem > startTime) {
                arr.unshift([newItem, st]);
                toLeftReverse(newItem);
            }
        }
        const start1 = new Date(data[0]['interval_zone'].split('~')[0]).getTime();
        toLeftReverse(start1);
        toRight(start1);
        return this._displayTime(arr);
    }
    // 转换时间戳为拼接时间格式 "2018-11-19~2018-11-26"
    _displayTime(xAxis: Array<[Date, Date]>) {
        const newX = [];
        xAxis.map(item => {
            newX.push(`${this.formatDate(item[0])}~${this.formatDate(item[1])}`);
        });
        return newX;
    }
    // 按周展示
    _setWeeklyOptions(data) {
        // const xAxis = this._displayXais(data);
        const seriesData1 = [];
        const seriesData2 = [];
        const series = [];

        let lang = localStorage.getItem('itmp_lang');

        let order = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

        if (lang !== 'en') {
            order = ['chủ nhật', 'thứ hai', 'thứ ba', 'thứ tư', 'thứ năm', 'thứ sáu', 'thứ bảy'];
        }

        const lastWeekData = data.filter(item => item.tag === 'LastWeek');
        const thisWeekData = data.filter(item => item.tag === 'ThisWeek');
        order.forEach(week => {
            const temp = lastWeekData.some(weekData => weekData.wk === week);
            if (!temp) {
                lastWeekData.push({
                    total: '0',
                    wk: week
                });
            }
            const temp1 = thisWeekData.some(weekData => weekData.wk === week);
            if (!temp1) {
                thisWeekData.push({
                    total: '0',
                    wk: week
                });
            }
        });
        lastWeekData.sort(function(a, b) {
            return order.indexOf(a.wk) - order.indexOf(b.wk);
        });
        thisWeekData.sort(function(a, b) {
            return order.indexOf(a.wk) - order.indexOf(b.wk);
        });
        lastWeekData.forEach(weekday => {
            seriesData1.push(weekday.total);
        });
        thisWeekData.forEach(weekday => {
            seriesData2.push(weekday.total);
        });
        const max = Math.max(...seriesData1.concat(seriesData2));
        const numPerSplit = Math.ceil(max / 4);

        if (lang == 'en') {
            this.options = {
                backgroundColor: '#363a70', //背景色
                grid: {
                    top: 35,
                    bottom: 30
                },
                legend: {
                    show: true,
                    textStyle: {
                        color: '#ffffff' //图例字体颜色
                    }
                },
                xAxis: {
                    show: true,
                    type: 'category',
                    boundaryGap: false,
                    splitLine: {
                        show: true
                    },
                    // data: xAxis
                    data: order,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    }
                },
                yAxis: {
                    show: true,
                    type: 'value',
                    max: numPerSplit * 5,
                    interval: numPerSplit,
                    splitLine: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            //Y轴座标文字颜色
                            color: '#fff'
                        }
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    // formatter: '{b} : {c}',
                    backgroundColor: 'rgba(0,71,157,0.5)'
                },
                color: ['#238CE6', '#fcd567'], //图例颜色
                series: [
                    //图例
                    {
                        name: 'Last Week',
                        type: 'line',
                        data: seriesData1,
                        symbol: 'circle'
                    },
                    {
                        name: 'This Week',
                        type: 'line',
                        data: seriesData2,
                        symbol: 'circle'
                    }
                ]
            };
        } else {
            this.options = {
                backgroundColor: '#363a70', //背景色
                grid: {
                    top: 35,
                    bottom: 30
                },
                legend: {
                    show: true,
                    textStyle: {
                        color: '#ffffff' //图例字体颜色
                    }
                },
                xAxis: {
                    show: true,
                    type: 'category',
                    boundaryGap: false,
                    splitLine: {
                        show: true
                    },
                    // data: xAxis
                    data: order,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    }
                },
                yAxis: {
                    show: true,
                    type: 'value',
                    max: numPerSplit * 5,
                    interval: numPerSplit,
                    splitLine: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            //Y轴座标文字颜色
                            color: '#fff'
                        }
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    // formatter: '{b} : {c}',
                    backgroundColor: 'rgba(0,71,157,0.5)'
                },
                color: ['#238CE6', '#fcd567'], //图例颜色
                series: [
                    //图例
                    {
                        name: 'Tuần trước',
                        type: 'line',
                        data: seriesData1,
                        symbol: 'circle'
                    },
                    {
                        name: 'Tuần này',
                        type: 'line',
                        data: seriesData2,
                        symbol: 'circle'
                    }
                ]
            };
        }
    }
    // 按年展示
    _setYearlyOptions(data) {
        const seriesData = [];
        this.tools.calc(data, 'year', []).forEach(item => {
            const itemData = {
                name: '',
                type: 'line',
                smooth: true,
                data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            };
            itemData.name = item;
            data.data[item].forEach(n => {
                itemData.data[n.month - 1] = n.total;
            });
            seriesData.push(itemData);
        });
        this.options = {
            xAxis: {
                show: true,
                type: 'category',
                boundaryGap: false,
                splitLine: {
                    show: true
                },
                data: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEPT', 'OCT', 'NOV', 'DEC']
            },
            yAxis: {
                show: true,
                type: 'value',
                splitLine: {
                    show: true
                }
            },
            legend: {
                orient: 'vertical',
                right: 0
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(0,71,157,0.5)'
            },
            series: seriesData
        };
    }
    // 过滤单选框
    filter(data) {
        this.searchData.interval = data;
        switch (data) {
            case 'Monthly': {
                this.placeHodlder = ['Up to', 'two years'];
                this.dateFormat = 'MM/yyyy';
                // if (this.updatedDate) {
                const startYear = new Date(this.updatedDate.length ? this.updatedDate[0] : this.startDefaultTime).getFullYear();
                const startMonth = new Date(this.updatedDate.length ? this.updatedDate[0] : this.startDefaultTime).getMonth() + 1;
                const endYear = new Date(this.updatedDate.length ? this.updatedDate[1] : this.endDefaultTime).getFullYear();
                const endMonth = new Date(this.updatedDate.length ? this.updatedDate[1] : this.endDefaultTime).getMonth() + 1;
                if (endYear - startYear >= 2) {
                    this.updatedDate = [];
                    this.searchData.startTime = null;
                    this.searchData.endTime = null;
                } else {
                    this.searchData.startTime = `${startYear}-${startMonth}-1`;
                    this.searchData.endTime = `${endYear}-${endMonth}`;
                }
                // }
                break;
            }
            case 'Yearly': {
                this.dateFormat = 'yyyy';
                this.placeHodlder = ['Start Time', 'End Time'];
                // if (this.updatedDate) {
                const startYear = new Date(this.updatedDate.length ? this.updatedDate[0] : this.startDefaultTime).getFullYear();
                const endYear = new Date(this.updatedDate.length ? this.updatedDate[1] : this.endDefaultTime).getFullYear();
                this.searchData.startTime = startYear + '-01-01';
                this.searchData.endTime = endYear + '-12-31';
                // }
                break;
            }
            case 'Weekly': {
                this.dateFormat = 'dd/MM/yyyy';
                // if (this.updatedDate) {
                this.searchData.startTime = this.updatedDate.length ? this.updatedDate[0] : this.startDefaultTime;
                this.searchData.endTime = this.updatedDate.length ? this.updatedDate[1] : this.endDefaultTime;
                // }
                this.placeHodlder = ['Start Time', 'End Time'];
                break;
            }
        }
        this._getData();
    }
    // 日历框事件
    onDateOk(result: Date[]): void {
        this.searchData.startTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : moment(this.startDefaultTime)
                  .startOf('day')
                  .valueOf();
        this.searchData.endTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : moment(this.endDefaultTime)
                  .endOf('day')
                  .valueOf();
        if (this.searchData.interval === 'Monthly') {
            const years =
                new Date(result[1] ? result[1] : this.endDefaultTime).getFullYear() -
                new Date(result[0] ? result[0] : this.startDefaultTime).getFullYear();
            if (years >= 2) {
                setTimeout(() => {
                    this.updatedDate = [];
                });
                this.searchData.startTime = null;
                this.searchData.endTime = null;
            }
        }
        this._getData();
    }
    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
